package com.shanzmoo.job.task;

import cn.hutool.core.util.EnumUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.MallOrderStatus;
import com.shanzmoo.base.constant.PayStatusConstant;
import com.shanzmoo.base.constant.e.PayTypeEnum;
import com.shanzmoo.core.config.pay.PayServiceConfig;
import com.shanzmoo.job.base.BaseTask;
import com.shanzmoo.core.manager.OutletOrderLogManager;
import com.shanzmoo.db.mall.entity.MallOrderEntity;
import com.shanzmoo.db.mall.service.IMallOrderService;
import com.shanzmoo.db.order.entity.OutletOrderEntity;
import com.shanzmoo.db.order.service.IOutletOrderService;
import com.shanzmoo.db.trade.entity.PayOrderEntity;
import com.shanzmoo.core.domain.pay.PayOrderEntityLocalUtil;
import com.shanzmoo.core.domain.pay.PayResultResp;
import com.shanzmoo.db.trade.service.IPayOrderBodyService;
import com.shanzmoo.db.trade.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 微信支付，结果查询
 *
 * @author： Gzhao 2021/1/16
 */
@Slf4j
@Component(value = "payOrderResultQueryTask")
public class PayOrderResultQueryTask implements BaseTask {;

    @Autowired
    private PayServiceConfig payServiceConfig;

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayOrderBodyService payOrderBodyService;

    @Autowired
    private IMallOrderService mallOrderService;

    @Autowired
    private IOutletOrderService outletOrderService;

    @Autowired
    private OutletOrderLogManager outletOrderLogManager;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String doJob() {

        /**
         * 1. 获取最多20条 未确认支付状态的微信支付订单
         */
        List<PayOrderEntity> payOrderList = payOrderService.list(
                new QueryWrapper<PayOrderEntity>()
//                        .eq("pay_no", "PAY202101242149352258631")
                        .eq("deleted", false)
                        .eq("status", true)
                        .eq("pay_status", PayStatusConstant.WAIT_PAY)
                        .orderByAsc("query_times")
                        .orderByDesc("create_time")
                        .last("limit 20")
        );

        for (PayOrderEntity payOrder : payOrderList) {
            /**
             * 2. 请求支付api，获取支付结果, 更新支付订单的状态
             */

            PayOrderEntityLocalUtil.setPayOrder(payOrder, payOrderBodyService.getByPayNo(payOrder.getPayNo()));

            SResponse<PayResultResp> re = payServiceConfig
                    .getPayService(EnumUtil.likeValueOf(PayTypeEnum.class, payOrder.getType()))
                    .queryPayResult(payOrder.getPayNo());

            if (!re.isOk()) {
                continue;
            }
            // 更新支付单信息
            PayOrderEntityLocalUtil.setReqBody(null);
            PayOrderEntityLocalUtil.setRespBody(null);
            payOrder.setQueryTimes(payOrder.getQueryTimes() + 1);
            payOrderService.updateByPayQuery(payOrder, PayOrderEntityLocalUtil.getPayOrderBodyEntity());

            /**
             * 3. 更新业务订单状态
             */
            if (re.getData().isSuccess()) {

                if (payOrder.getOrderNo().startsWith("MA")) {
                    // 商城订单
                    MallOrderEntity mallOrder = mallOrderService.getOne(
                            new QueryWrapper<MallOrderEntity>().eq("order_no", payOrder.getOrderNo())
                    );

                    if (mallOrder != null && !mallOrder.getPayStatus()){
                        mallOrder.setPayStatus(true);
                        mallOrder.setStatus(MallOrderStatus.WAIT_SEND);
                        mallOrder.setPayNo(payOrder.getPayNo());
                        mallOrder.setPayType(payOrder.getType());

                        mallOrderService.updateById(mallOrder);
                    }

                } else {
                    // 门店订单
                    OutletOrderEntity outletOrder = outletOrderService.getOne(
                            new QueryWrapper<OutletOrderEntity>().eq("order_no", payOrder.getOrderNo())
                    );

                    if (outletOrder != null && !outletOrder.getPayStatus()){
                        outletOrder.setPayStatus(true);
                        outletOrder.setPayNo(payOrder.getPayNo());

                        outletOrderService.updateById(outletOrder);
                        outletOrderLogManager.saveLog(outletOrder.getId(), "支付状态更新");
                    }
                }
            }
            PayOrderEntityLocalUtil.clear();
        }

        return "success";
    }
}
